// advice.js
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser')
const cors = require('cors');


const mysql = require('mysql2')

require('dotenv').config();
const dbserver = process.env.DB_SERVER
const dbUser = process.env.DB_USER;
const dbPass = process.env.DB_PASSWORD;
const dbname = process.env.DB_DATABASE


const pool = mysql.createPool({
  connectionLimit: 10, // 连接池中最大的连接数量
  host: dbserver, // 数据库的地址
  user: dbUser, // 数据库的用户名
  password: dbPass, // 数据库的密码
  database: dbname // 数据库的名称
});


router.use(cors())
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.text());


// 用户相关的路由
router.get('/getUserByUsername', (req, res) => {
  // 获取用户列表的逻辑
  let params = req.query
  let condtions = ""
  let username = params.username

  console.log(params)

  let userSQL = "select * from users "

  if (params.username !== undefined && params.username !== "") {
    condtions = condtions + " where username = '" + username + "'"
  }
  userSQL = userSQL + condtions

  console.log(userSQL);

  pool.query(userSQL, (err, results, fiedds) => {
    if (err) {
      console.log(err)
      res.json({ msg: 'query error' });
      return;
    }
    res.json({ data: results, code: '200', msg: '查询用户成功' })
  })
});

router.post('/register', (req, res) => {
  // 获取注册页面表单中的数据
  let { username, password, email, mobile } = req.body
  const now = new Date()

  let userSQL = "SELECT * FROM users WHERE username = '" + username + "'"
  console.log(userSQL)
  pool.query(userSQL, (err, results, fiedds) => {
    if (err) {
      console.log(err)
      res.json({ msg: 'query error' });
      return;
    }

    //当发现已经有账号时，提醒用户直接登录或者注册
    if (results.length >= 1) {
      res.json({ data: { hasUser: true }, code: '200', msg: '用户已经存在' })
      return;
    } else { //没有账号才执行插入用户数据。完成注册逻辑
      let insertSql = 'insert into users (username,password,email,mobile,create_time,update_time) values (?,?,?,?,?,?)'
      pool.query(insertSql, [username, password, email, mobile, now, now], (err, result, feilds) => {
        if (err) {
          console.log("insert into users error", err)
          res.json({ "error": err, "code": '500', "msg": '注册用户失败:' + err })
          return;
        }
        console.log("insert users ok")
        res.json({ data: 'success', "msg": '注册用户成功', "code": '200' })
      })
    }
  })




});






router.post('/login', (req, res) => {
  // 用户登录得逻辑

  // 获取用户列表的逻辑

  let isLogin = false
  let { username, password } = req.body

  let userSQL = "select * from users "

  let condtions = " where username = '" + username + "' and  password = '" + password + "'";

  userSQL = userSQL + condtions

  console.log("用户登录SQL:-->" + userSQL);

  pool.query(userSQL, (err, results, fiedds) => {
    if (err) {
      console.log(err)
      res.json({ msg: '用户登录发生异常', code: '500' });
      return;
    }
    if (results.length >= 1) {
      isLogin = true
      res.json({ "data": { isLogin: isLogin }, "code": '200', "msg": '用户登录成功' })
    } else {
      res.json({ "data": { isLogin: isLogin }, "code": '400', "msg": '用户名和密码不匹配' })
    }
  })
});


router.post('/auth', (req, res) => {
  // 用户验证得罗  auth
  res.json({ message: 'Usee is loged in' });
});

module.exports = router;